import router from './router'
import { asyncRoutes } from '@/router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
/* import { getToken } from '@/utils/auth' */
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')

      NProgress.done()
    } else {
      // 后台管理系统不能做持久化
      if (!store.getters.userId) {
        const menu = await store.dispatch('user/asyncInfo')
        const filterList = asyncRoutes.filter(item => {
          const a = item.children[0].name
          return menu.includes(a)
        })
        filterList.push(
          // 404 page must be placed at the end !!!
          { path: '*', redirect: '/404', hidden: true }
        )
        console.log(menu)
        router.addRoutes(filterList)
        store.commit('menu/setMenuList', filterList)
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        next()
      }

      NProgress.done()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
